﻿using System;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
//using Microsoft.Samples.VisualStudio.IronPython.Project;
using EnvDTE80;
using Microsoft.VisualStudio.Project;
//using Microsoft.Samples.VisualStudio.IronPython.Project.WPFProviders;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using System.ComponentModel.Design;
//using Microsoft.VisualStudio.Package;
using EnvDTE;
//using Microsoft.Samples.VisualStudio.IronPython.Project.Library;
using Microsoft.VisualStudio.OLE.Interop;
using Izhgtu.Library;


namespace Izhgtu.SandcastlePackage
{
    /// <summary>
    /// This is the class that implements the package exposed by this assembly.
    ///
    /// The minimum requirement for a class to be considered a valid package for Visual Studio
    /// is to implement the IVsPackage interface and register itself with the shell.
    /// This package uses the helper classes defined inside the Managed Package Framework (MPF)
    /// to do it: it derives from the Package class that provides the implementation of the 
    /// IVsPackage interface and uses the registration attributes defined in the framework to 
    /// register itself and its components with the shell.
    /// </summary>
    /// 
    /// 
   

    [ProvideToolWindowVisibility(typeof(ContentWindow), /*UICONTEXT_SolutionExists*/"65D42C96-F0E4-42B5-894D-9C6C0FDC0629")]
    [ProvideToolWindow(typeof(ContentWindow),
    Style = Microsoft.VisualStudio.Shell.VsDockStyle.Tabbed,
    Window = "3ae79031-e1bc-11d0-8f78-00a0c9110057")]

    [ProvideMenuResource(1000, 1)]
    [ProvideObject(typeof(GeneralPropertyPage))]
    [ProvideObject(typeof(SandcastleBuildPropertyPage))]
    //Set the projectsTemplatesDirectory to a non-existant path to prevent VS from including the working directory as a valid template path
    [ProvideProjectFactory(
    typeof(SandcastleProjectFactory),
    null,
    "Simple Project Documentation Files (*.shfbproj);*.shfbproj",
    "shfbproj", "shfbproj",
    ".\\NullPath",
    LanguageVsTemplate = "Sandcastle")]
    // This attribute tells the PkgDef creation utility (CreatePkgDef.exe) that this class is
    // a package.
    //// IronPython does not need a CodeBehindCodeGenerator because all the code should be inline, so we disable
    //// it setting a null GUID for the class that is supposed to implement it.
    //[WAProvideLanguageProperty(typeof(WAPythonProjectFactory), "CodeBehindCodeGenerator", "{00000000-0000-0000-0000-000000000000}")]
    [PackageRegistration(UseManagedResourcesOnly = true)]
    // This attribute is used to register the informations needed to show the this package
    // in the Help/About dialog of Visual Studio.

    [InstalledProductRegistration("#110", "#112", "1.0", IconResourceID = 400)]
    [Guid(GuidList.guidSandcastlePackagePkgString)]
    
    public sealed class SandcastlePackage : ProjectPackage, IVsInstalledProduct, IOleComponent
    {
        private SandcaslteLibraryManager libraryManager;
        private uint componentID;
        private int numberTopic = 0;
        /// <summary>
        /// Default constructor of the package.
        /// Inside this method you can place any initialization code that does not require 
        /// any Visual Studio service because at this point the package object is created but 
        /// not sited yet inside Visual Studio environment. The place to do all the other 
        /// initialization is the Initialize method.
        /// </summary>
        public SandcastlePackage()
        {
            Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering constructor for: {0}", this.ToString()));
        }



        /////////////////////////////////////////////////////////////////////////////
        // Overriden Package Implementation
        #region Package Members
        /// <summary>
        /// This function is the callback used to execute a command when the a menu item is clicked.
        /// See the Initialize method to see how the menu item is associated to this function using
        /// the OleMenuCommandService service and the MenuCommand class.
        /// </summary>
        private void MenuItemCallback(object sender, EventArgs e)
        {
            EnvDTE.DTE dte = (EnvDTE.DTE)Package.GetGlobalService(typeof(EnvDTE.DTE));
            EnvDTE.Project prj = dte.Solution.Projects.Item(1);



            ProjectItem prjItem;
            String nametopic = "NewTopic";


            String guid = Guid.NewGuid().ToString();
            // dte.Solution.Projects.Item(1).ProjectItems.AddFolder("sdfsd", guid);

            Solution2 soln = (Solution2)dte.Solution;
            string itemPath = soln.GetProjectItemTemplate("Glosary.zip", "Sandcastle");

            if (System.IO.File.Exists(itemPath))
            {

                prjItem = prj.ProjectItems.AddFromTemplate(itemPath, "NewTopic" + numberTopic.ToString());

                numberTopic++;
            }
        }

        /// <summary>
        /// This function is called when the user clicks the menu item that shows the 
        /// tool window. See the Initialize method to see how the menu item is associated to 
        /// this function using the OleMenuCommandService service and the MenuCommand class.
        /// </summary>
        public void ShowToolWindow(object sender, EventArgs e)
        {
            // Get the instance number 0 of this tool window. This window is single instance so this instance
            // is actually the only one.
            // The last flag is set to true so that if the tool window does not exists it will be created.
            ToolWindowPane window = this.FindToolWindow(typeof(ContentWindow), 0, true);
            if ((null == window) || (null == window.Frame))
            {
                throw new NotSupportedException("Не смогло создать содержание");
            }
            IVsWindowFrame windowFrame = (IVsWindowFrame)window.Frame;
            Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(windowFrame.Show());
        }


        /// <summary>
        /// Initialization of the package; this method is called right after the package is sited, so this is the place
        /// where you can put all the initilaization code that rely on services provided by VisualStudio.
        /// </summary>
        protected override void Initialize()
        {
            DTE dte = (DTE)GetService(typeof(DTE));
            if (dte != null)
            {
                base.Initialize();
                this.RegisterProjectFactory(new SandcastleProjectFactory(this));
                ShowToolWindow(null, null);



                // Add our command handlers for menu (commands must exist in the .vsct file)
                OleMenuCommandService mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService;
                if (null != mcs)
                {
                    // Create the command for the query status menu item.
                    CommandID queryStatusCommandID = new CommandID(GuidList.guidDynamicMenuDevelopmentCmdSetPart2, (int)PkgCmdIDList.cmdidQueryStatus);
                    OleMenuCommand queryStatusMenuCommand = new OleMenuCommand(MenuItemCallback, queryStatusCommandID);
                    //queryStatusMenuCommand.BeforeQueryStatus += new EventHandler(queryStatusMenuCommand_BeforeQueryStatus);
                    mcs.AddCommand(queryStatusMenuCommand);

                }



            }

            //IServiceContainer container = this as IServiceContainer;
            //container.AddService(typeof(ISandcastleLibraryManager), CreateService, true);

        }
        #endregion


        private object CreateService(IServiceContainer container, Type serviceType)
        {
            object service = null;
            //if (typeof(ISandcastleLibraryManager) == serviceType)
            //{
            //    libraryManager = new SandcaslteLibraryManager(this);
            //    service = libraryManager as ISandcastleLibraryManager;
            //    RegisterForIdleTime();
            //}
            return service;
        }

        private void RegisterForIdleTime()
        {
            IOleComponentManager mgr = GetService(typeof(SOleComponentManager)) as IOleComponentManager;
            if (componentID == 0 && mgr != null)
            {
                OLECRINFO[] crinfo = new OLECRINFO[1];
                crinfo[0].cbSize = (uint)Marshal.SizeOf(typeof(OLECRINFO));
                crinfo[0].grfcrf = (uint)_OLECRF.olecrfNeedIdleTime |
                                              (uint)_OLECRF.olecrfNeedPeriodicIdleTime;
                crinfo[0].grfcadvf = (uint)_OLECADVF.olecadvfModal |
                                              (uint)_OLECADVF.olecadvfRedrawOff |
                                              (uint)_OLECADVF.olecadvfWarningsOff;
                crinfo[0].uIdleTimeInterval = 1000;
                int hr = mgr.FRegisterComponent(this, crinfo, out componentID);
            }
        }

        protected override void Dispose(bool disposing)
        {
            try
            {
                if (componentID != 0)
                {
                    IOleComponentManager mgr = GetService(typeof(SOleComponentManager)) as IOleComponentManager;
                    if (mgr != null)
                    {
                        mgr.FRevokeComponent(componentID);
                    }
                    componentID = 0;
                }
                if (null != libraryManager)
                {
                    libraryManager.Dispose();
                    libraryManager = null;
                }
            }
            finally
            {
                base.Dispose(disposing);
            }
        }


        #region IVsInstalledProduct Members
        /// <summary>
        /// This method is called during Devenv /Setup to get the bitmap to
        /// display on the splash screen for this package.
        /// </summary>
        /// <param name="pIdBmp">The resource id corresponding to the bitmap to display on the splash screen</param>
        /// <returns>HRESULT, indicating success or failure</returns>
        public int IdBmpSplash(out uint pIdBmp)
        {
            pIdBmp = 300;

            return VSConstants.S_OK;
        }

        /// <summary>
        /// This method is called to get the icon that will be displayed in the
        /// Help About dialog when this package is selected.
        /// </summary>
        /// <param name="pIdIco">The resource id corresponding to the icon to display on the Help About dialog</param>
        /// <returns>HRESULT, indicating success or failure</returns>
        public int IdIcoLogoForAboutbox(out uint pIdIco)
        {
            pIdIco = 400;

            return VSConstants.S_OK;
        }

        /// <summary>
        /// This methods provides the product official name, it will be
        /// displayed in the help about dialog.
        /// </summary>
        /// <param name="pbstrName">Out parameter to which to assign the product name</param>
        /// <returns>HRESULT, indicating success or failure</returns>
        public int OfficialName(out string pbstrName)
        {
            pbstrName = GetResourceString("@ProductName");
            return VSConstants.S_OK;
        }

        /// <summary>
        /// This methods provides the product description, it will be
        /// displayed in the help about dialog.
        /// </summary>
        /// <param name="pbstrProductDetails">Out parameter to which to assign the description of the package</param>
        /// <returns>HRESULT, indicating success or failure</returns>
        public int ProductDetails(out string pbstrProductDetails)
        {
            pbstrProductDetails = GetResourceString("@ProductDetails");
            return VSConstants.S_OK;
        }

        /// <summary>
        /// This methods provides the product version, it will be
        /// displayed in the help about dialog.
        /// </summary>
        /// <param name="pbstrPID">Out parameter to which to assign the version number</param>
        /// <returns>HRESULT, indicating success or failure</returns>
        public int ProductID(out string pbstrPID)
        {
            pbstrPID = GetResourceString("@ProductID");
            return VSConstants.S_OK;
        }

        #endregion

        /// <summary>
        /// This method loads a localized string based on the specified resource.
        /// </summary>
        /// <param name="resourceName">Resource to load</param>
        /// <returns>String loaded for the specified resource</returns>
        public string GetResourceString(string resourceName)
        {
            string resourceValue;
            IVsResourceManager resourceManager = (IVsResourceManager)GetService(typeof(SVsResourceManager));
            if (resourceManager == null)
            {
                throw new InvalidOperationException("Could not get SVsResourceManager service. Make sure the package is Sited before calling this method");
            }
            Guid packageGuid = this.GetType().GUID;
            int hr = resourceManager.LoadResourceString(ref packageGuid, -1, resourceName, out resourceValue);
            Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(hr);
            return resourceValue;
        }

        public override string ProductUserContext
        {
            get
            {
                throw new NotImplementedException();
            }
        }

        public int FContinueMessageLoop(uint uReason, IntPtr pvLoopData, MSG[] pMsgPeeked)
        {
            return 1;
        }

        public int FDoIdle(uint grfidlef)
        {
            if (null != libraryManager)
            {
                libraryManager.OnIdle();
            }
            return 0;
        }

        public int FPreTranslateMessage(MSG[] pMsg)
        {
            return 0;
        }

        public int FQueryTerminate(int fPromptUser)
        {
            return 1;
        }

        public int FReserved1(uint dwReserved, uint message, IntPtr wParam, IntPtr lParam)
        {
            return 1;
        }

        public IntPtr HwndGetWindow(uint dwWhich, uint dwReserved)
        {
            return IntPtr.Zero;
        }

        public void OnActivationChange(IOleComponent pic, int fSameComponent, OLECRINFO[] pcrinfo, int fHostIsActivating, OLECHOSTINFO[] pchostinfo, uint dwReserved)
        {
        }

        public void OnAppActivate(int fActive, uint dwOtherThreadID)
        {
        }

        public void OnEnterState(uint uStateID, int fEnter)
        {
        }

        public void OnLoseActivation()
        {
        }

        public void Terminate()
        {
        }
    }
}
